package com.tony.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @version V1.0  </br>
 * @ClassName NIODemo1 </br>
 * @Description TODO  </br>
 * @Author tonywang</br>
 * @DATE 3/4/2019 2:27 PM</br>
 */
public class NIODemo1 {
    public void selector() throws IOException {
        //分配内存ByteBuffer
        ByteBuffer buffer  = ByteBuffer.allocate(1024);
        //创建Selector(调度器)
        Selector selector = Selector.open();
        //创建ServerSocketChannel(通信信道)
        ServerSocketChannel ssc = ServerSocketChannel.open();
        //设置非阻塞方式的Channel
        ssc.configureBlocking(false);
        //绑定端口(目标站)
        ssc.socket().bind(new InetSocketAddress(8080));
        //注册监听的事件(由Selector调度信道)
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            //获取所有key集合
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                //进入准备状态
                if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT ) {
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                    //接受客户端请求
                    SocketChannel sc = serverSocketChannel.accept();
                    sc.configureBlocking(false);
                    sc.register(selector,SelectionKey.OP_READ);
                    iterator.remove();
                } // 开门 下客
                else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    while (true) {
                        buffer.clear();
                        //读取数据
                        if (socketChannel.read(buffer) < 0) {
                            break;
                        }
                        buffer.flip();
                    }
                    iterator.remove();
                }
            }

        }


    }
}
